package com.theatre.userservice.ascept;

import com.theatre.userservice.annotation.RequirePermission;
import com.theatre.userservice.Controller.contxet.BaseContext;
import com.theatre.userservice.mapper.RoleFunctionMapper;
import com.theatre.userservice.model.vo.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private RoleFunctionMapper roleFunctionMapper;

    // 拦截带有 @RequirePermission 注解的方法
    @Pointcut("@annotation(requirePermission)")
    public void permissionPointcut(RequirePermission requirePermission) {}

    @Around("permissionPointcut(requirePermission)")
    public Object checkPermission(ProceedingJoinPoint joinPoint, RequirePermission requirePermission) throws Throwable {
        // 2. 解析角色 ID
        Long roleId = BaseContext.getCurrentId();
        // 3. 查询该角色拥有的权限
        List<String> permissions = roleFunctionMapper.selectPermissionsByRoleId(roleId);
        // 4. 校验接口权限
        String required = requirePermission.value();
        if(!permissions.contains(required)){
            return Result.error("权限不足");
        }
        // 5. 执行方法
        return joinPoint.proceed();
    }
}
